import time
import os
from collections import OrderedDict
from django.template import loader
from django.conf import settings


# cron 定时
# 初始化django环境是为了能够在当前的脚本运行测试

# 加载环境变量
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'MDmall.settings')

# 初始化django环境
import django
django.setup()


# 导入模型类

from goods.models import GoodsChannel
from contents.models import ContentCategory


def generate_static_index_html():
    """
    生成静态的主页html
    :return:
    """

    print('%s: generate_static_index' % time.ctime())
    # 定义所用的分类字典
    # OrderedDict有序字典
    categories = OrderedDict()

    # 获取一级分类
    channels = GoodsChannel.objects.order_by('group_id', 'sequence')

    # 对一级分类进行遍历

    for channel in channels:
        # 获取group_id
        group_id = channel.group_id
        # 判断group_id是否在存储容器,如果不在就初始化
        if group_id not in categories:
            categories[group_id] = {
                'channels': [],
                'sub_cats': []
            }
        # 取出一级分类
        one = channel.category

        # 为channels填充数据
        categories[group_id]['channels'].append({
            'id': one.id,
            'name': one.name,
            'url': channel.url
        })

        # 添加二级分类
        # 为sub_cats填充数据
        for two in one.goodscategory_set.all():
            # 初始化容器
            two.sub_cats = []
            # 遍历获取三级分类
            for three in two.goodscategory_set.all():
                two.sub_cats.append(three)

            # 组织数据
            categories[group_id]['sub_cats'].append(two)

    # 广告和首页数据
    contents = {}
    content_categories = ContentCategory.objects.all()
    for category in content_categories:
        contents[category.key] = category.content_set.filter(status=True).order_by('sequence')

    # 拼接分类,广告数据
    context = {
        'categories': categories,
        'contents': contents
    }

    # 获取模板
    template = loader.get_template('index.html')
    html_data = template.render(context)

    # 写入文件的地址
    file_path = os.path.join(settings.GENERATED_STATIC_HTML_FILES_DIR, 'index.html')
    with open(file_path, 'w', encoding='utf-8') as f:
        f.write(html_data)


if __name__ == '__main__':
    generate_static_index_html()




